<?php
namespace Api\Controller;

class ActivityController extends APIController {
    public $tbName = CONTROLLER_NAME; 

    /*待验证的参数*/
    public $tca = [
        'activity_id' => [
            'method' => 'exists',
            'model' => 'activity',
            'code_key' => 'lawless'
        ],
    ];
    /**
     * 列表页面
     */
    public function index() {
        try{
            $this->safeChecked();
            $page_num = I('param.page',C('PAGE'));
            $limit_num = I('param.show_num',C('SHOW_NUM'));
            if(!S('activities')){
                $Obj = D($this->tbName); //实例化对象
                //普通团的排序字段-开团数，价格
                $sales = array();
                $price = array();
                $type = I('param.type',1);//默认普通团
                //团列表
                $list = $Obj
                        ->where(array('type' => $type,'deleted' => 0,'hidden' => 0,'start' => array('lt',time()),'end' => array('gt',time())))
                        ->Field('goods_id,id,num')
                        ->order('crdate desc')
                        ->select();
                if($list){
                    $Group = M('group');
                    $Plan = M('plan');
                    $Goods = M('goods');
                    $Order = M('order');
                    foreach($list as $key => &$val){
                        //获取最低拼团价
                        $activity_price = $Plan->where(array('activity_id' => $val['id'],'deleted' => 0))->Field('group_price')->order('group_price asc')->limit(0,1)->select();
                        $val['price'] = $activity_price[0]['group_price'];
                        $price[] = $val['price'];
                        $goods = $Goods->Field('crdate,image,name,remark')->find($val['goods_id']);
                        $val['image'] = C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/'.date('Ym',$goods['crdate']).'/'.$goods['image'];
                        $val['name'] = $goods['name'];
                        $val['remark'] = explode(',', $goods['remark']);
                        //获取该活动下的所有开团数量
                        $groups = $Group->where(array('activity_id' => $val['id']))->Field('id')->select();
                        $group_ids = [];
                        if($groups){
                            $group_ids = array_map(function($val){
                                return $group_ids[] = $val['id'];
                            },$groups);
                        }
                        $val['sales'] = 0;
                        if($group_ids){
                            $val['sales'] = $Order->where(array('group_id' => array('IN',$group_ids)))->count()?:0;
                        }
                        $sales[] = $val['sales'];
                    }
                }
                $list = array_values($list);
                //团列表及排序字段排序缓存5分钟
                S('activities',$list,300);
                S('num',$num,300);
                S('price',$price,300);
            }else{
                $list = S('activities');
                $num = S('num');
                $price = S('price');
            }
            
            //排序
            if($list){
                //排序类型 0综合排序 拼团降序序,价格升序 1价格升序 2价格降序 3全部 创建时间倒序
                switch (I('param.sort')) {
                    case 0:
                        array_multisort($num,SORT_DESC,$price,SORT_ASC,$list);
                        break;
                    case 1:
                        array_multisort($price,SORT_ASC,$list);
                        break;
                    case 2:
                        array_multisort($price,SORT_DESC,$list);
                        break;
                    default:
                        break;
                }
            }
            //获取对应查询页码的数据
            if($list){
                $list = array_slice($list,($page_num - 1)*$limit_num,$limit_num);
            }
            $this->res_data['data'] = $list?:array();
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 活动详细
     */
    public function info(){
        try{
            static $data = array();
            $this->safeChecked();
            /*验证*/
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $activity_id = I('param.activity_id');
            $Obj = D($this->tbName); //实例化对象
            $activity = $Obj->find($activity_id);
            //开团优惠券
            $activity['coupon_money'] = $activity['group_coupon_id']?M('coupon')->where(array('id' => $activity['group_coupon_id']))->getField('money'):0;
            $data['activity'] = $activity;
            //商品价格方案
            $Plan = M('plan');
            $price_plans = $Plan
                        ->alias('a')
                        ->join(C('DB_PREFIX').'goods_info as b ON a.goods_info_id = b.id')
                        ->where(array('a.deleted' => 0,'a.activity_id' => $activity_id))
                        ->Field('a.goods_info_id,a.group_price,a.leader_price,b.assistant,b.stock,b.sale_price')
                        ->order('a.group_price ASC')
                        ->select();
            $data['plans'] = $price_plans;
            //商品
            $Goods = M('goods');
            $goods = $Goods->Field('id,name,remark,image,crdate,content,links,postage_price,title,service')->find($activity['goods_id']);
            $goods['image'] = C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/'.date('Ym',$goods['crdate']).'/'.$goods['image'];
            $goods['sales'] = M('order')->where(array('goods_id' => $goods['id']))->sum('num')?:0;
            $goods['comments'] = M('comment')->where(array('goods_id' => $goods['id']))->count()?:0;
            $goods['title'] = explode(',', $goods['title']);
            $goods['service'] = explode(',', $goods['service']);
            $data['goods'] = $goods;
            /*多图*/
            $Attach = M('attach');
            $attachs = $Attach->where(array('deleted' => 0,'info_tab' => 'Goods','info_id' => $activity['goods_id']))->Field('crdate,path')->select();
            $data['attach'] = array();
            if($attachs){
                foreach ($attachs as $key => $v) {
                   $data['attach'][] = C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/attach/'.date('Ym',$v['crdate']).'/'.$v['path'];
                }
            }
            /*商品详细*/
            /*$GoodsInfo = M('goods_info');
            $goods_info = $GoodsInfo->where(array('deleted' => 0,'goods_id' => $goods['id']))->Field('id,sale_price,assistant,stock')->order('sale_price ASC')->select();
            $data['goods_info'] = $goods_info;*/
            /*商品评价*/
            $Comment = M('comment');
            $comments = $Comment
                        ->alias('a')
                        ->join(C('DB_PREFIX').'member as b ON a.user_id = b.id')
                        ->where(array('a.goods_id' => $goods['id']))
                        ->Field('a.id,a.content,b.wxlogo,b.nickname')
                        ->limit(0,2)
                        ->select();
            if($comments){
                foreach ($commenets as $key => &$value) {
                    $attach = $Attach->where(array('deleted' => 0,'info_tab' => 'Comment','info_id' => $value['id']))->Field('crdate,path')->select();
                    $value['attach'] = [];
                    if($attach){
                        foreach ($attach as $key => $v) {
                           $value['attach'] = C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/attach/'.date('Ym',$v['crdate']).'/'.$v['path'];
                        }
                    }
                }
            }
            $data['comments'] = $comments?:[];
            //开团详情
            $Group = M('group');
            $where['a.complete_time'] = 0;
            $where['a.expired'] = array('gt',time());
            $where['a.activity_id'] = $activity_id;
            $where['a.state'] = 1;
            $user_id = I('param.user_id',0);
            /*if($user_id){
                $where['a.user_id'] = ['neq',$user_id];
            }*/
            $groups = $Group
                    ->alias('a')
                    ->join(C('DB_PREFIX').'member as b ON a.user_id = b.id')
                    ->where($where)
                    ->order('a.crdate desc')
                    ->Field('a.id,a.expired,b.nickname,b.wxlogo')
                    ->select();
            //存在开团,拼装两个团为一组数据
            $data['groups'] = array();
            $data['end_times'] = array();
            if($groups){
                $Order = M('order');
                foreach($groups as &$val){
                    //用户已登录,剔除调用用户已参团的团详情
                    if(!$user_id || !$Order->where(array('group_id' => $val['id'],'user_id' => $user_id))->count()){
                        //计算还差几人可完成拼团
                        $count = $Order->where(array('group_id' => $val['id']))->count();
                        $val['space'] = $activity['num'] - $count;
                        $data['groups'][] = $val;
                        $data['end_times'][] = date("Y-m-d H:i:s",$val['expired']);
                    }
                }
            }
            /*$num = 0;
            if($groups){
                $Order = M('order');
                foreach($groups as &$val){
                    //计算还差几人可完成拼团
                    $count = $Order->where(array('group_id' => $val['id']))->count();
                    $val['space'] = $activity['num'] - $count;
                    if(count($data['groups'][$num]) == 2){
                        ++$num;
                    }
                    $data['groups'][$num][] = $val;
                }
            }*/
            $this->res_data['data'] = $data;
        }catch(\Exception $e){
            p($e);
            debug([$e->getmessage(),$e->getline()]);
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 超级团长创建活动
     */
    public function createActivity(){
        try{
            static $data = array();
            $this->safeChecked();
            /*验证*/
            $this->tca = [
                'user_id' => [
                    'method' => 'exists',
                    'model' => 'member',
                    'code_key' => 'lawless'
                ],
                'is_support_coupon' => [
                    'method' => 'regex',
                    'model' => '/^[0-1]$/',
                    'code_key' => 'lawless'
                ],
                'auto_group' => [
                    'method' => 'regex',
                    'model' => '/^[0-1]$/',
                    'code_key' => 'lawless'
                ],
                'self_buy' => [
                    'method' => 'regex',
                    'model' => '/^[0-1]$/',
                    'code_key' => 'lawless'
                ],
                'goods_id' => [
                    'method' => 'exists',
                    'model' => 'Goods',
                    'code_key' => 'lawless'
                ],
                'info_id' => [
                    'method' => 'exists',
                    'model' => 'Goods_info',
                    'code_key' => 'lawless'
                ],
                'num' => [
                    'method' => 'regex',
                    'model' => '/\\d/',
                    'code_key' => 'lawless'
                ],
            ];
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            //用户是否为超级团长
            $Member = M('member');
            $data = I('param.');
            $user_info = $Member->find($data['user_id']);
            if(!$user_info['is_colonel']){
                $this->res_data['code_key'] = 'is_not_colonel'; //用户暂无建团权限
                $this->apiReply();
            }
            //判断人数
            if($data['num'] < 2){
                $this->res_data['code_key'] = 'num_too_lower'; //拼团人数不能小于2
                $this->apiReply();
            }
            //判断日期格式
            if(!strtotime($data['start'])){
                $this->res_data['code_key'] = 'date_deny'; //日期格式错误
                $this->apiReply();
            }
            //判断设置价格
            $goods_info = M('goods_info')->where(array('deleted' => 0,'goods_id' => $data['goods_id']))->Field('id,distribution_price')->order('distribution_price asc')->select();
            foreach ($data['group_price'] as $key => $value) {
                //判断价格格式
                if(!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $value)){
                    $this->res_data['code_key'] = 'money_type_deny'; //团购价格式错误
                    $this->apiReply();
                }
                //判断团购价金额
                if($value < $goods_info[array_search($data['goods_info_id'], $goods_info)]['distribution_price']){
                    $this->res_data['code_key'] = 'money_too_lower'; //团购价不能低于分销价
                    $this->apiReply();
                }
            }
            //保存活动
            $Obj = D($this->tbName);
            $Obj->startTrans();
            $start = strtotime($data['start']);
            $end = $start + 86400;
            $expired = 24;
            $param = [
                'type' => 3,
                'start' => $start,
                'end' => $end,
                'goods_id' => $data['goods_id'],
                'num' => $data['num'],
                'is_support_coupon' => $data['is_support_coupon'],
                'auto_group' => $data['auto_group'],
                'expired' => $expired,
                'user_id' => $data['user_id'],
                'crdate' => time(),
                'tstamp' => time()
            ];
            $id = $Obj->add($param);
            if(!$id){
                debug('保存活动失败');
                debug($Obj->_sql());
                $Obj->rollback();
                $this->res_data['code_key'] = 'fail';
                $this->apiReply();
            }
            //保存活动方案
            $Plan = M('plan');
            foreach($data['group_price'] as $key => $value){
                $plan_data = [
                    'activity_id' => $id,
                    'goods_info_id' => $data['goods_info_id'][$key],
                    'group_price' => $value
                ];
                $flag = $Plan->add($plan_data);
                if(!$flag){
                    debug('保存价格方案失败');
                    debug($Plan->_sql());
                    $Obj->rollback();
                    $this->res_data['code_key'] = 'fail';
                    $this->apiReply();
                }
            }
            //创建拼团
            $Group = M('group');
            $group_data = [
                'activity_id' => $id,
                'type' => 3,
                'num' => $data['num'],
                'auto_group' => $data['auto_group'],
                'user_id' => $data['user_id'],
                'goods_id' => $data['goods_id'],
                'goods_name' => M('goods')->where(array('id' => $data['goods_id']))->getField('name'),
                'expired' => $end,
                'crdate' => time(),
                'group_num' => date('YmdHis').$this->createRandomStr(),
                'state' => 1,
                'start' => time()
            ];
            $group_id = $Group->add($group_data);
            if(!$group_id){
                debug('新增拼团失败');
                debug($Plan->_sql());
                $Obj->rollback();
                $this->res_data['code_key'] = 'fail';
                $this->apiReply();
            }
            //判断是否虚拟参团
            if($data['self_buy']){
                $Goods = M('goods');
                $GoodsInfo = M('goods_info');
                $goods_info = $GoodsInfo->find($data['info_id']);
                //创建订单数据
                $order_data = array(
                    'group_id' => $group_id,
                    'order_num' => $this->Config['order_prefix'].date('YmdHis').$this->createRandomStr(),
                    'user_id' => $data['user_id'],
                    'goods_id' => $data['goods_id'],
                    'goods_name' => $Goods->where(array('id' => $data['goods_id']))->getField('name'),
                    'goods_info_id' => $data['info_id'],
                    'assistant' => $goods_info['assistant'],
                    'sku' => $goods_info['sku'],
                    'is_collect_bills' => 1,
                    'is_pay' => 1,
                    'crdate' => time(),
                    'tstamp' => time()
                );
                $order_id = M('order')->add($order_data);
                if(!$order_id){
                    debug('新增订单失败');
                    debug(M('order')->_sql());
                    $Obj->rollback();
                    $this->res_data['code_key'] = 'fail';
                    $this->apiReply();
                }
            }
            $Obj->commit();
        }catch(\Exception $e){
            debug([$e->getmessage(),$e->getline()]);
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 取消拼团
     */
    public function cancel(){
        try{
            static $data = array();
            $this->safeChecked();
            /*验证*/
            $this->tca = [
                'user_id' => [
                    'method' => 'exists',
                    'model' => 'member',
                    'code_key' => 'lawless'
                ],
                'activity_id' => [
                    'method' => 'exists',
                    'model' => 'activity',
                    'code_key' => 'lawless'
                ],
            ];
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            //用户是否为活动创建者
            $Obj = D($this->tbName);
            $data = I('param.');
            $info = $Obj->find($data['activity_id']);
            if($info['user_id'] = $data['user_id']){
                $this->res_data['code_key'] = 'lawless'; //用户暂无建团权限
                $this->apiReply();
            }
            //取消活动
            $Obj = D($this->tbName);
            $Obj->startTrans();
            $param = [
                'hidden' => 1,
                'tstamp' => time()
            ];
            $flag = $Obj->where(array('id' => $activity_id))->save($param);
            if(!$flag){
                debug('取消活动失败');
                debug($Obj->_sql());
                $Obj->rollback();
                $this->res_data['code_key'] = 'fail';
                $this->apiReply();
            }
            $Obj->commit();
        }catch(\Exception $e){
            debug([$e->getmessage(),$e->getline()]);
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 删除拼团
     */
    public function del(){
        try{
            static $data = array();
            $this->safeChecked();
            /*验证*/
            $this->tca = [
                'user_id' => [
                    'method' => 'exists',
                    'model' => 'member',
                    'code_key' => 'lawless'
                ],
                'activity_id' => [
                    'method' => 'exists',
                    'model' => 'activity',
                    'code_key' => 'lawless'
                ],
            ];
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            //用户是否为活动创建者
            $Obj = D($this->tbName);
            $data = I('param.');
            $info = $Obj->find($data['activity_id']);
            if($info['user_id'] = $data['user_id']){
                $this->res_data['code_key'] = 'lawless'; //用户暂无建团权限
                $this->apiReply();
            }
            //取消活动
            $Obj = D($this->tbName);
            $Obj->startTrans();
            $param = [
                'deleted' => 1,
                'tstamp' => time()
            ];
            $flag = $Obj->where(array('id' => $activity_id))->save($param);
            if(!$flag){
                debug('删除活动失败');
                debug($Obj->_sql());
                $Obj->rollback();
                $this->res_data['code_key'] = 'fail';
                $this->apiReply();
            }
            $Obj->commit();
        }catch(\Exception $e){
            debug([$e->getmessage(),$e->getline()]);
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }
}

?>